package com.my.servlet;

import com.my.controal.JDBC;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/BuyTicket")
public class BuyTicket extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理中文乱码
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String userID = request.getParameter("userID");
        String trainID = request.getParameter("trainID");
        int seatType = Integer.parseInt(request.getParameter("seatType"));
        String seatNumber = request.getParameter("seatNumber");
        int countt = Integer.parseInt(request.getParameter("countt"));
        int inventor = Integer.parseInt(request.getParameter("inventor"));

        // 查询库存中有没有相同数据
        String selesql = String.format("SELECT * FROM tb_showmy WHERE userID='%s' AND trainID='%s' AND seatType=%d AND seatNumber='%s'", userID, trainID, seatType, seatNumber);
        int ticketCount = 0;

        try {
            ResultSet res = JDBC.Instance().selectTable(selesql);

            // 当查询到重复数据时 不新插入，而是对原来的购票数量做修改
            if(res.next()) {
                ticketCount = res.getInt("countt");

                String sql = String.format("update tb_showmy set countt=%d where userID='%s' and seatType=%d",  ticketCount + countt, userID, seatType);
                JDBC .Instance().querySQLCommand(sql);
            }
            else {
                String sql = String.format("INSERT INTO tb_showmy VALUES(null, '%s', '%s', %d, '%s', %d)", userID, trainID, seatType, seatNumber, countt);
                JDBC.Instance().querySQLCommand(sql);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            // 执行库存-1的操作
            String sql1 = String.format("update tb_ticket set inventor=%d where trainID='%s'", inventor - countt, trainID);

            JDBC .Instance().querySQLCommand(sql1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
